package net.cjw.initsb.config.quartz.configrefresh;

import javax.annotation.Resource;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import net.cjw.initsb.common.ServiceResult;
import net.cjw.initsb.entity.QuartzTask;
import net.cjw.initsb.service.QuartzTaskServiceI;

@Configuration
@EnableScheduling
@Component
public class ScheduleRefreshDatabase {

	Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private QuartzTaskServiceI quartzTaskServiceI;

	// sayHello任务
	@Resource(name = "jobDetailSayHello")
	private JobDetail jobDetailSayHello;

	@Resource(name = "jobTriggerSayHello")
	private CronTrigger cronTriggerSayHello;

	// sayHi任务
	@Resource(name = "jobDetailSayHi")
	private JobDetail jobDetailSayHi;

	@Resource(name = "jobTriggerSayHi")
	private CronTrigger cronTriggerSayHi;

	@Resource(name = "scheduler")
	private Scheduler scheduler;

	// 检查数据库配置
	@Scheduled(fixedRate = 5000) // 每隔5s查库，并根据查询结果决定是否重新设置定时任务
	public void scheduleUpdateCronTrigger() throws SchedulerException {
		checkTrigger(cronTriggerSayHello);
		checkTrigger(cronTriggerSayHi);
	}

	private void checkTrigger(CronTrigger trigger) throws SchedulerException {
		// 获取当前信息
		TriggerKey tk = trigger.getKey();
		String tkGroup = tk.getGroup();
		String tkName = tk.getName();
		JobKey jk = trigger.getJobKey();
		String jkName = jk.getName();
		String jkGroup = jk.getGroup();
		String description = trigger.getDescription();
		trigger = (CronTrigger) scheduler.getTrigger(tk);
		String currentCron = trigger.getCronExpression();// 当前Trigger使用的
		// logger.info("currentCron: " + currentCron);
		// logger.info("jkName: " + jkName);
		// 查询数据库
		QuartzTask qt = new QuartzTask();
		qt.setCronExpression(currentCron);
		qt.setDescription(description);
		qt.setJobGroup(jkGroup);
		qt.setJobName(jkName);
		qt.setTriggerName(tkName);
		qt.setTriggerGroup(tkGroup);
		ServiceResult<QuartzTask> sr = quartzTaskServiceI.selectOne(qt);

		QuartzTask rs = null;
		if (sr.isSuccess()) {
			rs = sr.getData();
		}

		if (rs.getIsPause()) {
			// logger.info("暂停任务 tk: " + tk);
			scheduler.pauseTrigger(tk);
		} else {
			// logger.info("恢复任务 tk: " + tk);
			scheduler.resumeTrigger(tk);
		}
		// 假设数据库查出来的结果
		// String searchCron = "0/5 * * * * ?";
		String searchCron = rs.getCronExpression();

		if (currentCron.equals(searchCron)) {
			// 如果当前使用的cron表达式和从数据库中查询出来的cron表达式一致，则不刷新任务
		} else {
			// logger.info("更新cron表达式 tk: " + tk);
			// 表达式调度构建器
			CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(searchCron);
			// 按新的cronExpression表达式重新构建trigger
			trigger = trigger.getTriggerBuilder().withIdentity(tk).withSchedule(scheduleBuilder).build();
			// 按新的trigger重新设置job执行
			scheduler.rescheduleJob(tk, trigger);
		}
	}

}